#include <REGX52.H>

sbit I2C_SCL = P2^1;
sbit I2C_SDA = P2^0;

/**
  * @brief   I2C开始
  * @details 
  * @param   	
  * @retval  
  */
void I2C_Start() {
	I2C_SDA = 1;
	I2C_SCL = 1;
	I2C_SDA = 0;
	I2C_SCL = 0;
}

/**
  * @brief   I2C停止
  * @details 
  * @param   
  * @retval  
  */
void I2C_Stop() {
	I2C_SDA = 0;
	I2C_SCL = 1;
	I2C_SDA = 1;
}

/**
  * @brief   I2C发送一个字节数据
  * @details 
  * @param   
  * @retval  
  */
void I2C_SendByte(unsigned char byte) {
	char i = 7;
	while (i >= 0) {
		I2C_SDA = (byte >> i) & 0x01;
		I2C_SCL = 1;
		I2C_SCL = 0;
		i--;
	}
}

/**
  * @brief   I2C接收一个字节数据
  * @details 
  * @param   
  * @retval  
  */
unsigned char I2C_ReceiveByte() {
	unsigned char byte = 0, i;
	I2C_SDA = 1;
	for (i = 0; i < 8; i++) {
		I2C_SCL = 1;
		if (I2C_SDA)
			byte |= 0x80 >> i;
		I2C_SCL = 0;
	}
	return byte;
}

/**
  * @brief   I2C发送应答
  * @details 
  * @param   ack 0为应答，1为非应答
  * @retval  
  */
void I2C_SendAck(unsigned char ack) {
	I2C_SDA = ack;
	I2C_SCL = 1;
	I2C_SCL = 0;
}

/**
  * @brief   I2C接收应答
  * @details 
  * @param   
  * @retval  0为应答，1为非应答
  */
unsigned char I2C_ReceiveAck() {
	unsigned char ack;
	I2C_SDA = 1;
	I2C_SCL = 1;
	ack = I2C_SDA;
	I2C_SCL = 0;
	return ack;
}